package jmine.tec.persist.schema.impl.elements;

import java.util.List;

import javax.persistence.SequenceGenerator;

import jmine.tec.persist.schema.api.AbstractProcessingSchemaElement;
import jmine.tec.persist.schema.api.ProcessingSchemaElement;
import jmine.tec.persist.schema.api.SqlDialect;

/**
 * Elemento que representa uma sequence
 * 
 * @author lundberg
 */
public class SequenceElement extends AbstractProcessingSchemaElement<SequenceGenerator> implements Comparable<SequenceElement> {

    // valor inicial padrão definido na anotação
    private static final int DEFAULT_ANNOTATION_INITIAL_VALUE = 1;

    // valor inicial definido pelo jTec
    public static final long DEFAULT_INITIAL_VALUE = 100000;

    private final String name;

    private Integer initialValue;

    private String tableName;

    /**
     * Construtor
     * 
     * @param name nome da sequence
     * @param parent parent
     */
    public SequenceElement(String name, ProcessingSchemaElement<?> parent) {
        super(parent);
        this.name = name;
    }

    /**
     * Obtém o nome da sequence
     * 
     * @return nome da sequence
     */
    public String getName() {
        return this.name;
    }

    /**
     * {@inheritDoc}
     */
    public List<String> createStatements(SqlDialect dialect) {
        return dialect.renderSequence(this.name, this.initialValue);
    }

    /**
     * Processa a sequence, obtendo o valor inicial da anotação, já que o hibernate não sabe ler esse campo e criar a sequence corretamente.
     * 
     * @param annotation annotation
     */
    public void process(SequenceGenerator annotation) {
        if (annotation.initialValue() == DEFAULT_ANNOTATION_INITIAL_VALUE) {
            this.initialValue = (int) DEFAULT_INITIAL_VALUE;
        } else {
            this.initialValue = annotation.initialValue();
        }
    }

    /**
     * Define o valor inicial da sequence
     * 
     * @param initialValue valor inicial desejado
     */
    public void setInitialValue(Integer initialValue) {
        this.initialValue = initialValue;
    }

    /**
     * {@inheritDoc}
     */
    public int compareTo(SequenceElement o) {
        return this.name.compareTo(o.name);
    }

    /**
     * @return the tableName
     */
    public String getTableName() {
        return this.tableName;
    }

    /**
     * @param tableName the tableName to set
     */
    public void setTableName(String tableName) {
        this.tableName = tableName;
    }

    /**
     * @return the initialValue
     */
    public Integer getInitialValue() {
        return this.initialValue;
    }
}
